// backend/src/routes/api/auth.js
const express = require('express');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const User = require('../../models/user');
const config = require('../../config/default');
const logger = require('../../utils/logger');
const router = express.Router();

// 创建初始用户路由
router.post('/create', async (req, res) => {
    try {
        // 检查是否已存在管理员用户
        const existingAdmin = await User.findOne({ username: 'admin' });
        if (existingAdmin) {
            return res.status(400).json({ message: 'Admin user already exists' });
        }

        // 创建新的管理员用户
        const hashedPassword = await bcrypt.hash('admin', 10);
        const user = new User({
            username: 'admin',
            password: hashedPassword,
            role: 'admin'
        });
        await user.save();
        logger.info('Admin user created successfully');
        res.json({ message: 'Admin user created successfully' });
    } catch (error) {
        logger.error('Error creating admin user:', error);
        res.status(500).json({ message: 'Error creating user', error: error.message });
    }
});

// 登录路由
router.post('/login', async (req, res) => {
    try {
        const { username, password } = req.body;
        logger.info(`Login attempt for user: ${username}`);

        // 查找用户
        const user = await User.findOne({ username });
        if (!user) {
            logger.warn(`Login failed: User ${username} not found`);
            return res.status(401).json({ message: 'Invalid credentials' });
        }

        // 验证密码
        const isValid = await bcrypt.compare(password, user.password);
        if (!isValid) {
            logger.warn(`Login failed: Invalid password for user ${username}`);
            return res.status(401).json({ message: 'Invalid credentials' });
        }

        // 生成 token
        const token = jwt.sign(
            {
                userId: user._id,
                username: user.username,
                role: user.role
            },
            config.jwt.secret,
            { expiresIn: config.jwt.expiresIn }
        );

        // 更新最后登录时间
        user.lastLogin = new Date();
        await user.save();

        logger.info(`User ${username} logged in successfully`);
        res.json({
            token,
            user: {
                username: user.username,
                role: user.role,
                lastLogin: user.lastLogin
            }
        });
    } catch (error) {
        logger.error('Login error:', error);
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

module.exports = router;
